package com.kujie.websocket.handler;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.Map;

import static com.kujie.websocket.constant.WebSocketConstants.LOGIN_USER_KEY;

/**
 * @author sean.zhou
 * @version 0.1
 * @date 2021/11/16
 */
@Slf4j
public class AuthPrincipalHandler extends DefaultHandshakeHandler {

    @Override
    protected boolean isValidOrigin(ServerHttpRequest request) {
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            try {
                String parameter = servletRequest.getParameter("token");
                if(StringUtils.hasText(parameter)){
                    System.out.println(parameter);
                }
                System.out.println("WebSocket 认证成功");
//                LoginUser loginUser = LoginHelper.getLoginUser();
//                servletRequest.setAttribute(LOGIN_USER_KEY, loginUser);
                servletRequest.setAttribute(LOGIN_USER_KEY, "root");
                return true;
            } catch (Exception e) {
                log.error("WebSocket 认证失败'{}',无法访问系统资源", e.getMessage());
                return false;
            }
        }
        return false;
    }

    /**
     * The principal's name: {workspaceId}/{userType}/{userId}
     *
     * @param request
     * @param wsHandler
     * @param attributes
     * @return
     */
    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        if (request instanceof ServletServerHttpRequest) {
            String user = (String) ((ServletServerHttpRequest) request).getServletRequest().getAttribute(LOGIN_USER_KEY);
//            LoginUser loginUser = (LoginUser) ((ServletServerHttpRequest) request).getServletRequest().getAttribute(LOGIN_USER_KEY);
//            return () -> loginUser.getTenantId() + "/" + loginUser.getUserType() + "/" + loginUser.getUserId();
            return () -> user;
        }
        return () -> null;
    }

}